<template>
  <div class="dashboard-container">
    <h2>{{ isAdd ? "新增内容" : "编辑内容" }}</h2>
    <div class="dashboard-text">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题：" prop="title">
          <el-input
            v-model="ruleForm.title"
            :maxlength="20"
            show-word-limit
            placeholder="请输入标题"
          />
        </el-form-item>

        <el-form-item label="详细介绍：" prop="introduce">
          <el-input
            v-model="ruleForm.introduce"
            show-word-limit
            :maxlength="200"
            type="textarea"
            placeholder="请输入详细介绍"
          />
        </el-form-item>

        <el-form-item label="类别：" prop="categoryId">
          <el-cascader
            v-model="ruleForm.categoryId"
            :options="categoryList"
            :props="{
              value:'id',
              label:'name',
              emitPath:true
            }"
          />
        </el-form-item>

        <el-form-item label="封面：" prop="cover">
          <div>
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :action="action"
              accept=".jpg, .jpeg, .JPG, .JPEG, .png, .PNG"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
            >
              <img v-if="ruleForm.cover" :src="ruleForm.cover" class="avatar">
              <i v-else class="el-icon-plus" />
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="文章内容：" prop="content">
          <Tinymce
            ref="tinymceRef"
            height="50vh"
            width="50vw"
            @input="handleSetContent"
            @load="handleGetContent"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSaveContent">{{
            this.isAdd ? "新建" : "保存"
          }}</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import {
  addArticleLearningStudyDetail, addKnowledgeDetail,
  getArticleLearningStudyDetail, getKnowledgeDetail,
  updateArticleLearningStudyDetail, updateKnowledgeDetail
} from '@/api/knowledge'
import {getCategoryList, getCategoryListAll} from '@/api/category'
import Tinymce from '@/components/Tinymce/index.vue'
export default {
  name: 'Dashboard',
  components: { Tinymce },
  data() {
    return {
      action: process.env.VUE_APP_BASE_UPLOAD,
      ruleForm: {
        content: '',
        introduce: '',
        title: '',
        cover: '',
        categoryId: ''
      },
      dialogVisible: false,
      dialogImageUrl: '',
      contentId: null,
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        introduce: [
          { required: true, message: '请输入详细介绍', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        cover: [{ required: true, message: '请选择封面', trigger: 'blur' }],
        categoryId: [
          {
            required: true,
            message: '请选择类别',
            trigger: 'blur'
          }
        ]
      },
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      listLoading: false,
      categoryList: []
    }
  },
  computed: {
    isAdd({ $route }) {
      return $route.query.type === 'add'
    }
  },
  created() {
    this.handleGetCategory()
  },
  methods: {
    async handleGetCategory() {
      const res = await getCategoryList()
      if (res.code === 200) {
        this.categoryList = res.data
      }
    },
    async handleGetContent() {
      if (this.$route.query.id) {
        const res = await getKnowledgeDetail({
          id: this.$route.query.id
        })
        if (res.code === 200) {
          this.ruleForm = res.data || ''
          this.$nextTick(() => {
            this.$refs.tinymceRef.setContent(res.data?.content || '')
          })
        }
      } else {
        this.$nextTick(() => {
          this.$refs.tinymceRef.setContent('')
        })
      }
    },
    handleSetContent(e) {
      console.log(e)
      this.ruleForm.content = e
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.ruleForm.pics = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess(response, file, fileList) {
      if (response.code === 200) {
        file.url = response.data
        this.ruleForm.cover = file.url
      }
    },
    handleSaveContent() {
      console.log('保存')
      this.$refs.ruleForm.validate(async(valid) => {
        console.log(valid)
        if (valid) {
          const api = this.isAdd
            ? addKnowledgeDetail
            : updateKnowledgeDetail
          const { content, title, pics, categoryId, introduce,cover } = this.ruleForm
          const obj = {
            content,
            title,
            cover,
            categoryId,
            introduce
          }
          if (!this.isAdd) {
            obj.id = this.ruleForm.id
          }
          const res = await api({
            ...obj
          })
          if (res.data && res.code === 200) {
            this.$message.success(`保存成功`)
            this.$router.back()
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    padding: 0 30px;
  }
}
.el-input,
.el-textarea {
  width: 300px;
}
.avatar{
  border: 1px solid #999999;
  width: 200px;
  height: 300px;
  object-fit: contain;
}
</style>
